package com.li;


import java.util.ArrayList;
import java.util.List;

/**
 * @author lirenchun
 */
public class SimilarityUtil {

    public static void main(String[] args) {
        System.out.println(levenshtein("豫A3366X","豫A7655X"));
        System.out.println(plateSimilarity("豫A3366X","豫A7655X"));
    }
    /**
     * 相似度算法
     *
     * @param str1
     * @param str2
     */
    public static float levenshtein(String str1, String str2) {
        //计算两个字符串的长度。
        int len1 = str1.length();
        int len2 = str2.length();
        //建立上面说的数组，比字符长度大一个空间
        int[][] dif = new int[len1 + 1][len2 + 1];
        //赋初值，步骤B。
        for (int a = 0; a <= len1; a++) {
            dif[a][0] = a;
        }
        for (int a = 0; a <= len2; a++) {
            dif[0][a] = a;
        }
        //计算两个字符是否一样，计算左上的值
        int temp;
        for (int i = 1; i <= len1; i++) {
            for (int j = 1; j <= len2; j++) {
                if (str1.charAt(i - 1) == str2.charAt(j - 1)) {
                    temp = 0;
                } else {
                    temp = 1;
                }
                //取三个值中最小的
                dif[i][j] = min(dif[i - 1][j - 1] + temp, dif[i][j - 1] + 1,
                        dif[i - 1][j] + 1);
            }
        }
        //取数组右下角的值，同样不同位置代表不同字符串的比较
        //计算相似度
        float similarity = 1 - (float) dif[len1][len2] / Math.max(str1.length(), str2.length());
       return  similarity;
    }

    //得到最小值
    private static int min(int... is) {
        int min = Integer.MAX_VALUE;
        for (int i : is) {
            if (min > i) {
                min = i;
            }
        }
        return min;
    }

    public  static float plateSimilarity(String plateA,String plateB ){
        float plateSimilar=0;
        float plateSimilarTemp=0;
        List<String> splitPlateAList = splitPlate(plateA);
        List<String> splitPlateBList = splitPlate(plateB);
        //外循环车牌A切割后集合,内循环车牌B切割后集合,判断是否有相同字符串，判断相似度
        for (String strA : splitPlateAList
        ) {
            for (String strB:splitPlateBList
            ) {
                if(strA.equals(strB)){
                    plateSimilarTemp=strA.length()/(float)plateA.length();
                    if(plateSimilar<plateSimilarTemp){
                        plateSimilar=plateSimilarTemp;
                    }
                    System.out.println("相似片段:"+strA);
                }
            }
        }
        return plateSimilar;
    }


    public static List<String> splitPlate(String plate) {
        List<String> splitPlateList = new ArrayList<>();
        for (int iIndex = 0; iIndex < plate.length(); iIndex++) {
            for (int jIndex = iIndex + 1; jIndex <= plate.length(); jIndex++) {
                splitPlateList.add(plate.substring(iIndex, jIndex));
            }
        }
        return splitPlateList;
    }
}
